const db = require("../db/index");

// 获取所有用户
exports.getAllUser = (req, res) => {
  // express-jwt 中间件，自动解析token，然后挂载到 req.user
  console.log(req.user);
  let { id } = req.user;
  let { page, size } = req.body;
  // 判断用户是不是管理员有没有权限
  let sqlStr = "select is_admin from ev_users where id = ?";
  db.query(sqlStr, id, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) {
      return res.send({
        status: "1",
        message: "你的身份信息校验失败，请联系管理员！",
      });
    }
    let is_admin = results[0].is_admin;
    // is_admin == 1 ? 管理员 : 普通用户
    if (is_admin) {
      sqlStr = "select * from ev_users limit ? , ?";
      let pz = (page - 1) * size;
      size = size * 1;
      db.query(sqlStr, [pz, size], (err, results) => {
        if (err) return res.cc(err);
        // 获取所有数据的条数
        let total = 0;
        let queryTotalStr = "select count(*) as total from ev_users";
        db.query(queryTotalStr, null, (err, results2) => {
          total = results2[0]["total"];
          // 把用户的密码清除
          results.forEach((item) => {
            item.password = "";
          });
          res.send({
            status: "0",
            message: "获取所有用户信息成功！",
            data: { results, total },
          });
        });
      });
    }
  });
};
